package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.entity.User;
import com.chen.pfm.utils.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AbsButton;
import ohos.agp.components.Button;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Text;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;

public class AppGradeSlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "BillDetailsSlice");
    private int grade = 0;
    Button submit;
    Text gradeText;
    String gradeContent = "";
    User user;
    Gson gson;
    ResultVo resultVo;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_app_grade);
        gson = new Gson();
        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener((component) -> {
            terminate();
        });
        gradeText = (Text) findComponentById(ResourceTable.Id_gradeText);

        submit = (Button) findComponentById(ResourceTable.Id_submit);

        submit.setClickedListener((component -> {
            HiLog.info(LABEL, "用户已经提交评价！" + grade);
            MyToast.showMyToast(this, "评价已提交评价..." + grade);
            //更新服务器
            String uid = DataBaseUtil.GetValue(this, "uid");
            if (uid != null) {
                user = UserDBUtil.queryOneByUid(this, Integer.valueOf(uid));
                if (user == null) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "用户信息不存在");
                    });

                    return;
                } else {

                    try {
                        int update = UserDBUtil.update(this, user);
                        if (update > 0) {

                            MyToast.showMyToast(this, "感谢您的评价...");

                            updateRemoteData(MyUtil.updateGradeByUid, null);
                        }
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }


                }
            }
        }));
        initCheckbox();
    }

    private void updateRemoteData(String url, Object sendJsonObject) {
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            user.setGrade(String.valueOf(grade));
            String getRequestjson = null;
            RequestBody requestBody = new FormBody.Builder()
                    .add("uid", String.valueOf(user.getUid()))
                    .add("grade", String.valueOf(grade))
                    .build();
            //转化为json
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, requestBody);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                HiLog.info(LABEL, "无法连接到网络！");
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "无法连接到网络");
                });
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {//这里必须用Exception接收
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }
                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });

                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                    });
                }

            }


        });
    }

    private void getGrade(AbsButton component, boolean state) {
        getUITaskDispatcher().asyncDispatch(() -> {
            if (state) {
                grade += 1;
            } else {
                grade -= 1;
            }
            if (grade == 0) {
                gradeContent = "非常差";
            } else if (grade == 1) {
                gradeContent = "差";
            } else if (grade == 2) {
                gradeContent = "一般";
            } else if (grade == 3) {
                gradeContent = "良好";
            } else if (grade == 4) {
                gradeContent = "满意";
            } else if (grade == 5) {
                gradeContent = "十分满意";
            }

            gradeText.setText(gradeContent);
        });

    }

    // 初始化Checkbox
    private void initCheckbox() {
        Checkbox checkbox1 = (Checkbox) findComponentById(ResourceTable.Id_check_box_1);
        Checkbox checkbox2 = (Checkbox) findComponentById(ResourceTable.Id_check_box_2);
        Checkbox checkbox3 = (Checkbox) findComponentById(ResourceTable.Id_check_box_3);
        Checkbox checkbox4 = (Checkbox) findComponentById(ResourceTable.Id_check_box_4);
        Checkbox checkbox5 = (Checkbox) findComponentById(ResourceTable.Id_check_box_5);
        checkbox1.setCheckedStateChangedListener((component, state) -> getGrade(component, state));
        checkbox2.setCheckedStateChangedListener((component, state) -> getGrade(component, state));
        checkbox3.setCheckedStateChangedListener((component, state) -> getGrade(component, state));
        checkbox4.setCheckedStateChangedListener((component, state) -> getGrade(component, state));
        checkbox5.setCheckedStateChangedListener((component, state) -> getGrade(component, state));

    }


}
